import * as XLSX from 'xlsx';
import convertToExcelFormat from '@/utils/convertToExcelFormat';

/**
 * 导出Excel文件
 * @param {Object} data - UniverSheet数据结构，包含sheets等
 * @param {string} fileName - 导出文件名（不含扩展名）
 */
export function exportExcel(data, fileName = '导出Excel') {
    if (!data || !data.sheets) {
        throw new Error('无效的Excel数据');
    }
    // 创建一个工作簿
    const workbook = XLSX.utils.book_new();
    // 遍历每个工作表并将其添加到工作簿中
    Object.keys(data.sheets).forEach(sheetId => {
        const sheet = data.sheets[sheetId];
        const sheetData = sheet.cellData;
        const excelFormat = convertToExcelFormat(sheetData);
        // 兼容空表
        if (excelFormat['!ref'] === 'A1:\x00-Infinity') excelFormat['!ref'] = 'A1:A2';
        XLSX.utils.book_append_sheet(workbook, excelFormat, sheet.name || sheetId);
    });
    XLSX.writeFile(workbook, `${fileName}.xlsx`, { compression: true });
} 